/**
 * 简化版位置选择工具
 * 主要使用微信原生API，避免第三方API依赖问题
 */

export interface SimpleLocationInfo {
  name: string;
  address: string;
  latitude: number;
  longitude: number;
}

export class SimpleLocationHelper {
  
  /**
   * 使用微信原生地图选择位置
   * @param options 选择选项
   * @returns Promise<SimpleLocationInfo>
   */
  static chooseLocation(options?: {
    latitude?: number;
    longitude?: number;
  }): Promise<SimpleLocationInfo> {
    return new Promise((resolve, reject) => {
      // 直接尝试选择位置，如果权限不足会自动提示
      this.doChooseLocation(options, resolve, reject);
    });
  }

  /**
   * 执行位置选择
   */
  private static doChooseLocation(
    options: any,
    resolve: (value: SimpleLocationInfo) => void,
    reject: (reason: any) => void
  ) {
    const chooseOptions: any = {
      success: (res: any) => {
        console.log('选择位置成功:', res);
        
        const locationInfo: SimpleLocationInfo = {
          name: res.name || '',
          address: res.address || '',
          latitude: res.latitude,
          longitude: res.longitude
        };
        
        resolve(locationInfo);
      },
      fail: (err: any) => {
        console.error('选择位置失败:', err);
        
        if (err.errMsg.includes('cancel')) {
          // 用户取消，不显示错误
          reject(new Error('用户取消选择'));
        } else if (err.errMsg.includes('auth deny') || err.errMsg.includes('authorize')) {
          // 权限被拒绝，引导用户开启权限
          wx.showModal({
            title: '位置权限',
            content: '需要获取您的位置信息来选择商家地址，请在设置中开启位置权限',
            confirmText: '去设置',
            cancelText: '取消',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting && settingRes.authSetting['scope.userLocation']) {
                      wx.showToast({
                        title: '权限已开启，请重新选择',
                        icon: 'none'
                      });
                    }
                  }
                });
              }
            }
          });
          reject(new Error('位置权限被拒绝'));
        } else {
          wx.showToast({
            title: '选择位置失败',
            icon: 'none'
          });
          reject(new Error('选择位置失败'));
        }
      }
    };

    // 如果提供了初始位置，设置地图中心点
    if (options?.latitude && options?.longitude) {
      chooseOptions.latitude = options.latitude;
      chooseOptions.longitude = options.longitude;
    }

    wx.chooseLocation(chooseOptions);
  }

  /**
   * 获取当前位置
   * @param highAccuracy 是否高精度定位
   * @returns Promise<SimpleLocationInfo>
   */
  static getCurrentLocation(highAccuracy: boolean = false): Promise<SimpleLocationInfo> {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: highAccuracy,
        highAccuracyExpireTime: 4000,
        success: (res) => {
          console.log('获取当前位置成功:', res);
          
          const locationInfo: SimpleLocationInfo = {
            name: '当前位置',
            address: `纬度:${res.latitude.toFixed(6)}, 经度:${res.longitude.toFixed(6)}`,
            latitude: res.latitude,
            longitude: res.longitude
          };
          
          resolve(locationInfo);
        },
        fail: (err) => {
          console.error('获取当前位置失败:', err);
          
          if (err.errMsg.includes('auth deny') || err.errMsg.includes('authorize')) {
            wx.showModal({
              title: '位置权限',
              content: '需要获取您的位置信息，请在设置中开启位置权限',
              confirmText: '去设置',
              cancelText: '取消',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting && settingRes.authSetting['scope.userLocation']) {
                        wx.showToast({
                          title: '权限已开启，请重新获取位置',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
            reject(new Error('位置权限被拒绝'));
          } else if (err.errMsg.includes('timeout')) {
            wx.showToast({
              title: '定位超时，请重试',
              icon: 'none'
            });
            reject(new Error('定位超时'));
          } else {
            wx.showToast({
              title: '获取位置失败',
              icon: 'none'
            });
            reject(new Error('获取位置失败'));
          }
        }
      });
    });
  }

  /**
   * 打开地图查看位置
   * @param location 位置信息
   */
  static openLocation(location: SimpleLocationInfo): Promise<void> {
    return new Promise((resolve, reject) => {
      wx.openLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        name: location.name,
        address: location.address,
        scale: 16,
        success: () => {
          console.log('打开地图成功');
          resolve();
        },
        fail: (err) => {
          console.error('打开地图失败:', err);
          wx.showToast({
            title: '打开地图失败',
            icon: 'none'
          });
          reject(err);
        }
      });
    });
  }

  /**
   * 带确认的位置选择
   * @param currentLocation 当前位置
   * @returns Promise<SimpleLocationInfo>
   */
  static chooseLocationWithConfirm(currentLocation?: SimpleLocationInfo): Promise<SimpleLocationInfo> {
    return new Promise(async (resolve, reject) => {
      try {
        const options = currentLocation ? {
          latitude: currentLocation.latitude,
          longitude: currentLocation.longitude
        } : undefined;

        const selectedLocation = await this.chooseLocation(options);
        
        // 显示确认对话框
        wx.showModal({
          title: '确认地址',
          content: `您选择的地址是：\n${selectedLocation.address}\n${selectedLocation.name}`,
          confirmText: '确认',
          cancelText: '重新选择',
          success: (res) => {
            if (res.confirm) {
              resolve(selectedLocation);
            } else {
              // 用户选择重新选择，递归调用
              this.chooseLocationWithConfirm(currentLocation)
                .then(resolve)
                .catch(reject);
            }
          }
        });
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 验证坐标是否有效
   * @param latitude 纬度
   * @param longitude 经度
   * @returns boolean
   */
  static isValidCoordinate(latitude: number, longitude: number): boolean {
    return latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180;
  }

  /**
   * 格式化地址显示
   * @param location 位置信息
   * @param maxLength 最大显示长度
   * @returns 格式化后的地址字符串
   */
  static formatAddressDisplay(location: SimpleLocationInfo, maxLength: number = 50): string {
    let displayText = location.address;
    
    if (location.name && location.name !== location.address && location.name !== '当前位置') {
      displayText = `${location.address} (${location.name})`;
    }
    
    if (displayText.length > maxLength) {
      displayText = displayText.substring(0, maxLength - 3) + '...';
    }
    
    return displayText;
  }
}

// 导出
module.exports = {
  SimpleLocationHelper,
  LocationHelper: SimpleLocationHelper, // 兼容原有代码
  MapSelector: {
    chooseLocationWithConfirm: SimpleLocationHelper.chooseLocationWithConfirm.bind(SimpleLocationHelper),
    smartChooseLocation: SimpleLocationHelper.chooseLocation.bind(SimpleLocationHelper)
  },
  AddressInput: {
    formatAddressDisplay: SimpleLocationHelper.formatAddressDisplay.bind(SimpleLocationHelper)
  }
};
